import 'package:cbec_app/components/base/base_customize_segmented_control.dart';
import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/common/count_down_timer.dart';
import 'package:cbec_app/components/common/not_found.dart';
import 'package:cbec_app/pages/goods/controller/bargaining_ctr.dart';
import 'package:cbec_app/pages/goods/entity/activity_item_entity.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../binding/goods_detail_binding.dart';
import 'goods_detail_page.dart';

//砍价页面
class BargainingPage extends GetView<BargainingController> {
  const BargainingPage({super.key});

  List<Widget> _createItemWidgets() {
    final BargainingController controller = Get.find<BargainingController>();
    List<Widget> widgetArr = [];
    for (int i = 0; i < controller.itemList.length; i++) {
      ActivityItemEntity item = controller.itemList[i];
      int selectIndex = controller.selected;
      if (i == 0) {
        widgetArr.add(
          Container(
            padding: const EdgeInsets.only(left: 5, top: 5, bottom: 0, right: 5),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CountDownTimer(
                  timeStamp: DateTime.parse(item.endtime ?? '').millisecondsSinceEpoch,
                  timeStyle: TimeStyle.hhmmss,
                  countDownStyle: CountDownStyle.box,
                  boxBackgroundColor: Tools.fromHex("#000000"),
                  colonColor: Tools.fromHex("#000000"),
                  style: setTextStyle(
                    12,
                    FontWeight.w400,
                    Tools.fromHex('#FFFFFF'),
                  ),
                  callback: () {},
                ),
                const SizedBox(
                  height: 5,
                ),
                Text(
                  '正在抢购',
                  style: TextStyle(
                    color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'),
                  ),
                ),
              ],
            ),
          ),
        );
      } else {
        widgetArr.add(
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                item.begintime ?? '',
                style: TextStyle(
                  color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'),
                ),
              ),
              const SizedBox(
                height: 3,
              ),
              Text(
                '即将开始',
                style: TextStyle(color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'), fontWeight: FontWeight.w500, fontSize: 12),
              ),
            ],
          ),
        );
      }
    }
    return widgetArr;
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<BargainingController>(builder: (controller) {
      return Scaffold(
        extendBodyBehindAppBar: true, // 允许 body 从 AppBar 顶部开始布局
        appBar: AppBar(
          backgroundColor: Colors.transparent, // 设置透明
          leading: IconButton(
            icon: const Icon(
              Icons.arrow_back,
              color: Colors.black,
            ),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            //自适应高度的图片
            Stack(
              children: [
                SizedBox(
                  width: double.infinity,
                  child: Image.asset("assets/images/kanjia_bg.png", fit: BoxFit.fitWidth),
                ),
                //const topRightBox(),
              ],
            ),

            // 分段控件
            SizedBox(
              height: 60,
              child: BaseCustomizeSegmentedControl(
                items: _createItemWidgets(),
                selectedIndex: controller.selected,
                onChanged: (index) {
                  controller.change(index);
                },
              ),
            ),

            // 列表
            Expanded(
              child: controller.goodsList.isNotEmpty
                  ? Tools.getPullRefresh(
                      enablePullDown: true,
                      enablePullUp: true,
                      refreshController: controller.baseRefreshCtr,
                      onRefresh: controller.onPageRefresh,
                      onLoading: controller.onPageLoading,
                      child: ListView.builder(
                          controller: controller.scrollController,
                          padding: EdgeInsets.zero, // 移除默认的内边距
                          itemCount: controller.goodsList.length,
                          itemBuilder: (context, index) {
                            final Map item = controller.goodsList[index];
                            return bargainingListItem(item: item);
                          }))
                  : const NotFound(),
            ),
          ],
        ),
      );
    });
  }
}

//砍价列表ITEM
class bargainingListItem extends StatelessWidget {
  final Map item;

  const bargainingListItem({
    super.key,
    required this.item,
  });

  @override
  Widget build(BuildContext context) {
    return BaseInteractive(
      onClick: () {
        final id = item['goodsId'];
        Get.to(
          () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
          routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
          arguments: {"id": id}, // 传递其它参数
          binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
        );
      },
      childWidget: Container(
        height: 132.w,
        margin: EdgeInsets.all(8.w),
        decoration: border_radis(Colors.white),
        child: Stack(
          children: [
            Positioned(
                child: Container(
              margin: EdgeInsets.all(10.w),
              child: Row(
                children: [
                  BaseImage(
                    url: item['mainImage'],
                    width: 110.w,
                    height: 110.w,
                    borderRadius: BorderRadius.circular(10),
                  ),
                  SizedBox(width: 10.w),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        width: 210.w,
                        child: Text(item['commodityName'], style: setTextStyle(14, FontWeight.w500, Tools.fromHex("#333333"))),
                      ),
                      item['commodityType'] == 0
                          ? goodsTypeTag("一般贸易")
                          : item['commodityType'] == 1
                              ? goodsTypeTag("保税")
                              : item['commodityType'] == 2
                                  ? goodsTypeTag("海外直邮")
                                  : emptyWidget(),
                      SizedBox(
                        width: 210.w,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Text("最低可砍至￥", style: setTextStyle(12, FontWeight.w300, Tools.fromHex("#F97C36"))),
                                    Text(
                                      item['hagglePrice'].toString().split('.')[0],
                                      style: setTextStyle(
                                        15,
                                        FontWeight.w700,
                                        Tools.fromHex("#F97C36"),
                                      ),
                                    ),
                                    Text(
                                      ".${item['hagglePrice'].toString().split('.')[1]}",
                                      style: setTextStyle(
                                        12,
                                        FontWeight.w300,
                                        Tools.fromHex("#F97C36"),
                                      ),
                                    ),
                                  ],
                                ),
                                Text("原价${item['price'].toString()}", style: setTextStyle(10, FontWeight.w300, Tools.fromHex("#999999")))
                              ],
                            ),
                            solidButton("发起砍价", fontsize: 12, width: 72, radius: 72 / 2, () {
                              final id = item['goodsId'];
                              Get.to(
                                () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
                                routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
                                arguments: {"id": id}, // 传递其它参数
                                binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
                              );
                            })
                          ],
                        ),
                      )
                    ],
                  )
                ],
              ),
            )),
            Positioned(
                left: 0.0.w,
                top: 10.w,
                child: Container(
                  alignment: Alignment.center,
                  width: 50.w,
                  height: 22.w,
                  decoration: BoxDecoration(
                    borderRadius: const BorderRadius.only(
                      topRight: Radius.circular(10.0),
                      bottomRight: Radius.circular(10.0),
                    ),
                    gradient: LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      colors: [Tools.fromHex("#FE6B1B"), Tools.fromHex("#FE2917")],
                    ),
                  ),
                  child: Text("砍价中", style: setTextStyle(10, FontWeight.w500, Tools.fromHex("#F3F5F7"))),
                )),
          ],
        ),
      ),
    );
  }
}

//顶部固定的砍价和规则按钮
class topRightBox extends StatelessWidget {
  const topRightBox({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Positioned(
        right: 1,
        top: 20,
        child: Column(
          children: [
            BaseInteractive(
              onClick: () => {},
              childWidget: Container(
                alignment: Alignment.center,
                padding: EdgeInsets.all(4.w),
                decoration: border_radis(Tools.fromHex("#CD2534"), radiusValue: 5),
                child: Text(
                  "规\n则",
                  style: setTextStyle(
                    12,
                    FontWeight.w300,
                    Tools.fromHex("#FFFFFF"),
                  ),
                ),
              ),
            ),
            SizedBox(height: 10.h),
            BaseInteractive(
              onClick: () => {},
              childWidget: Container(
                alignment: Alignment.center,
                padding: EdgeInsets.all(4.w),
                decoration: border_radis(Tools.fromHex("#CD2534"), radiusValue: 5),
                child: Text(
                  "我\n的\n砍\n价",
                  style: setTextStyle(
                    12,
                    FontWeight.w300,
                    Tools.fromHex("#FFFFFF"),
                  ),
                ),
              ),
            ),
          ],
        ));
  }

  @override
  String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
    super.toString();
    return 'Positioned';
  }
}
